#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>
#include <string.h>
#include <errno.h>
#include <malloc.h>

int global_int = 1;
int main()
{
    int local_int = 1;
    int *malloc_int = (int *)malloc(sizeof(int));
    *malloc_int = 1;
    pid_t pid = fork();
    if (pid == 0)
    {
        /*子进程代码*/
        local_int = 0;   //修改局部变量
        global_int = 0;  //修改全局变量
        *malloc_int = 0; //修改堆区变量
        fprintf(stdout, "[child] child change local global malloc value to 0.\n");
        free(malloc_int); //释放堆区变量
        sleep(10);        //休眠10秒，测试父进程等待
        fprintf(stdout, "[child] child exit.\n");
        exit(0);
    }
    else if (pid > 0)
    {
        /*父进程代码*/
        fprintf(stdout, "[parent] wait child exit\n");
        waitpid(pid, NULL, 0); //等待子进程结束
        fprintf(stdout, "[parent] child exited!\n");
        printf("[parent] gloabl_int = %d\n", global_int);
        printf("[parent] local_int = %d\n", local_int);
        printf("[parent] *malloc_int = %d\n", *malloc_int);
        free(malloc_int); //再次释放
    }
    else
    {
        /*派生出错*/
        fprintf(stderr, "fork failed! (%s)\n", strerror(errno));
        exit(1);
    }
    return 0;
}